package com.cybertron.ironhide.spider;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.cybertron.ironhide.spider.domain.SeedUrl;
import com.cybertron.ironhide.spider.task.Task;
import com.cybertron.ironhide.spider.xml.Site;

public class SpiderExecutor {

	private SiteManager siteManager;

	public SpiderExecutor() {
	}

	public void run(SeedUrl seedUrl) {
		Collection<Task> seedTasks = new ArrayList<Task>();

		Site site = getSite(seedUrl);
		if (site == null) {
			return;
		}
		seedUrl.counter = new Counter();
		seedTasks
				.add(new Task(seedUrl, seedUrl.getUrl(), null, true, site, 10));

		// 运行种子任务
		for (Task task : seedTasks) {
			task.isSource = true;
			Spider seedSpider = new Spider(task, task.site,
					siteManager.getListener());
			siteManager.getPool().execute(seedSpider);
		}
	}

	public Site getSite(SeedUrl seedUrl) {
		String url = seedUrl.getUrl();
		if (StringUtils.isNotBlank(url)) {
			try {
				String host = new URL(url).getHost();
				Map<String, Site> sites = siteManager.getSites();
				Site site = sites.get(StringUtils.lowerCase(host));
				return site;
			} catch (Exception e) {
				return null;
			}
		}
		return null;
	}

	public void setSiteManager(SiteManager siteManager) {
		this.siteManager = siteManager;
	}

}